<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item class="pull-right">
          <el-button class="pull-right" type="primary" size="small" @click="addEditClick()">新增卡头</el-button>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formInline.clevice_id"
            placeholder="卡头ID"
            @keyup.enter.native="searchClick"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formInline.machine_id"
            placeholder="机台ID"
            @keyup.enter.native="searchClick"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="small">
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1+(currentPage-1)*20}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="卡头ID" prop="id" width="80"></el-table-column>
        <el-table-column align="center" label="卡头编号" prop="clevice_no"></el-table-column>
        <el-table-column align="center" label="卡头类型" prop="type" min-width="110">
          <template slot-scope="scope">
            {{scope.row.type==0 ?'常规卡头':scope.row.type==1 ?'湖心岛门票区门票':scope.row.type==2
            ?'湖心岛门票区陪同票':scope.row.type==3 ?'湖心岛门票区销售':'-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="会员价" prop="coins_sell_vip"></el-table-column>
        <el-table-column align="center" label="非会员价" prop="coins_sell"></el-table-column>
        <el-table-column align="center" label="星星数" prop="stars"></el-table-column>
        <el-table-column align="center" label="脉冲数" prop="pulse"></el-table-column>
        <el-table-column align="center" label="次数" prop="times"></el-table-column>
        <el-table-column align="center" label="所属机台ID" prop="machine_id"></el-table-column>
        <el-table-column align="center" label="所属机台类型" prop="machine_type"></el-table-column>
        <el-table-column align="center" label="支持关联礼品">
          <template slot-scope="scope">{{scope.row.is_gift_mapping ==1? '支持' : '不支持'}}</template>
        </el-table-column>
        <el-table-column align="center" label="关联礼品" prop="gift_name" min-width="130"></el-table-column>
        <el-table-column align="center" label="备注" width="100" prop="remark"></el-table-column>
        <el-table-column align="center" label="扫码支付套餐">
          <template slot-scope="scope">
            <el-button
              :disabled="scope.row.combo_id*1<=0"
              @click="scanSetClick(scope.row,scope.$index)"
              type="primary"
              size="mini"
            >设置</el-button>
          </template>
        </el-table-column>
        <!-- 列表的操作按钮 -->
        <el-table-column align="center" label="操作" width="140">
          <template slot-scope="scope">
            <el-button
              @click="addEditClick(scope.row.id,scope.$index)"
              type="primary"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
            <el-button
              @click="delClick(scope.row.id,scope.$index)"
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        :title="dialogTitle"
        :visible.sync="addCleviceDialog"
        @close="callOf('saveForm')"
      >
        <el-form
          :model="saveForm"
          :inline="true"
          ref="saveForm"
          :rules="rules"
          style="width:620px;margin:0 auto;"
        >
          <el-form-item label="　会员价" prop="coins_sell_vip">
            <el-input v-model="saveForm.coins_sell_vip" class="w200" :disabled="isDisabled"></el-input>
          </el-form-item>
          <el-form-item class="pull-right" label="非会员价" prop="coins_sell">
            <el-input v-model="saveForm.coins_sell" class="w200" :disabled="isDisabled"></el-input>
          </el-form-item>
          <el-form-item label="　脉冲数" prop="pulse">
            <el-input v-model="saveForm.pulse" class="w200" :disabled="isDisabled"></el-input>
          </el-form-item>
          <el-form-item class="pull-right" label="星星数" prop="stars">
            <el-input
              onkeypress="return event.which>=48&&event.which<=57"
              v-model="saveForm.stars "
              class="w200"
              :disabled="isDisabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="卡头类型" prop="type">
            <el-select placeholder="卡头类型" v-model="saveForm.type" filterable>
              <el-option
                v-for="item in clevice_type"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="pull-right" label="· 备　注">
            <el-input :maxlength="50" v-model="saveForm.remark" class="w200"></el-input>
          </el-form-item>
          <br />
          <el-form-item>
            <el-checkbox class="w200" v-model="isGiftMapping" label="支持关联礼品" border></el-checkbox>
          </el-form-item>
          <el-form-item class="pull-right" label="次数" prop="times">
            <el-input
              onkeypress="return event.which>=48&&event.which<=57"
              v-model="saveForm.times "
              class="w200"
              :disabled="isDisabled"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveClick('saveForm')">确 定</el-button>
          <el-button @click="callOf('saveForm')">取 消</el-button>&nbsp;
        </div>
      </el-dialog>
      <!-- 扫码设置弹框 -->
      <el-dialog :close-on-click-modal="false" title="修改扫码套餐" :visible.sync="scanSetDialog">
        <div style="position:relative;top:-20px;">
          卡头ID：{{package_info.id}}
          &#x3000;&#x3000;卡头编号：{{package_info.clevice_no}} &#x3000;&#x3000;所属品牌：{{package_info.brand_name}}
        </div>
        <el-checkbox v-model="is_sweep" @change="sweepChange">支持扫码支付</el-checkbox>
        <br />
        <br />
        <el-checkbox :disabled="!is_sweep" v-model="is_mida" @change="midaChange">咪哒KTV</el-checkbox>&#x3000;
        <el-select
          :disabled="is_mida||!is_sweep"
          placeholder="套餐"
          size="mini"
          v-model="scanForm.combo_id"
          filterable
          @change="mealChange"
        >
          <el-option
            v-for="item in package_list"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <br />
        <br />
        <el-table
          highlight-current-row
          :data="scanForm.rules"
          v-loading.body="listLoading"
          border
          size="mini"
        >
          <el-table-column align="center" label="按钮" width="80">
            <template slot-scope="scope">
              <span class="indexColor">按钮{{scope.$index+1}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="扫码金额（元）" prop="money"></el-table-column>
          <el-table-column v-if="!is_mida" align="center" label="游玩次数（次）" prop="times"></el-table-column>
          <el-table-column v-if="is_mida" align="center" label="游玩时间（分钟）" prop="times"></el-table-column>
          <el-table-column align="center" label="首单赠送" width="80" v-if="!is_mida">
            <template slot-scope="scope">
              <el-checkbox disabled v-model="scope.row.is_give"></el-checkbox>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" size="small" @click="scanSaveClick">保 存</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination
        class="pull-left"
        background
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="20"
        layout="prev, pager, next, jumper"
        :total="totalDataNumber"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getList,
  getPage,
  delClevice,
  getEditMachine,
  getClevice,
  saveClevice,
  get_package,
  scanSave,
} from "@/api/information/deployclevice";
import { num1to255, nullOr1to255, integer1to999999999 } from "@/utils/validate";
export default {
  data() {
    const validateVal = (rule, value, callback) => {
      if (!num1to255(value)) {
        callback(new Error("请输入1-255数字"));
      } else {
        callback();
      }
    };
    const validateVal2 = (rule, value, callback) => {
      if (!nullOr1to255(value)) {
        callback(new Error("可不填，要填就填1-255数字"));
      } else {
        callback();
      }
    };
    const validateVal3 = (rule, value, callback) => {
      if(!value=='' && !integer1to999999999(value)){
        callback(new Error("可不填，要填就填大于0的数字"));
      }else {
        callback();
      }
    };
    return {
      package_list: [],
      package_info: {},
      mida_list: [
        { money: "15", times_first: "3", times: "3" },
        { money: "25", times_first: "5", times: "5" },
        { money: "40", times_first: "8", times: "8" },
        { money: "50", times_first: "10", times: "10" },
        { money: "75", times_first: "15", times: "15" },
      ],
      scanSetDialog: false,
      is_sweep: false,
      is_mida: false,
      clevice_type: [
        { id: "0", name: "常规卡头" },
        { id: "1", name: "湖心岛门票区门票" },
        { id: "2", name: "湖心岛门票区陪同票" },
        { id: "3", name: "湖心岛门票区销售" },
      ],
      machineInfo: "",
      isGiftMapping: false,
      isDisabled: false,
      isAdd: true,
      dialogTitle: "",
      editIndex: "",
      searchCleviceInfo: "",
      clevice_id: "",
      url: "",
      list: null,
      listLoading: false,
      currentPage: 1,
      totalDataNumber: 0,
      scanForm: {
        id: "",
        combo_id: "",
        rules: [{ money: "", times: "", times_first: "", is_give: false }],
      },
      formInline: {
        machine_id: "",
        clevice_id: "",
        brand_id: 0,
        store_id: 0,
        area_id: 0,
        machine_no: 0,
      },
      saveForm: {
        machine_id: this.$route.params.machine_id,
        coins_sell_vip: "",
        coins_sell: "",
        pulse: "",
        remark: "",
        type: "",
        stars: "",
        is_gift_mapping: "",
        times:""
      },
      newForm: {},
      rules: {
        coins_sell_vip: [
          { required: true, trigger: "blur", validator: validateVal },
        ],
        coins_sell: [
          { required: true, trigger: "blur", validator: validateVal },
        ],
        pulse: [{ required: true, trigger: "blur", validator: validateVal }],
        stars: [{ required: false, trigger: "blur", validator: validateVal2 }],
        type: [{ required: true, message: "选择卡头类型", trigger: "change" }],
        times: [{ required: false, trigger: "blur", validator: validateVal3 }],
      },
      addCleviceDialog: false,
      innerVisible: false,
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    sweepChange() {
      if (!this.is_sweep) {
        this.is_mida = false;
        this.scanForm.combo_id = "";
        this.scanForm.rules = [];
        return;
      }
    },
    midaChange() {
      this.scanForm.rules = [];
      if (this.is_mida) {
        this.scanForm.combo_id = "";
        this.scanForm.rules = this.mida_list;
        console.log(this.mida_list);
        return;
      }
      this.mealChange();
    },
    mealChange() {
      let item_list =
        this.scanForm.combo_id == ""
          ? []
          : this.package_list.filter((item, i) => {
              return item.id == this.scanForm.combo_id;
            })[0].rules;
      item_list.forEach((val) => {
        val.is_give = val.times_first * 1 > val.times * 1 ? true : false;
      });
      this.scanForm.rules = item_list;
      if (this.is_mida && this.scanForm.combo_id == "") {
        this.scanForm.rules = this.mida_list;
      }
    },
    scanSaveClick() {
      let data = {};
      data.id = this.scanForm.id;
      data.combo_id = this.scanForm.combo_id;
      data.is_sweep = this.is_sweep ? 1 : 0;
      if (this.is_mida) {
        data.combo_id = "6";
      }
      if (this.is_sweep && !this.is_mida && this.scanForm.combo_id == "") {
        this.$message({ type: "error", message: "请选择套餐" });
        return;
      }
      console.log(data);
      scanSave(data).then((response) => {
        this.$message({ type: "success", message: response.message });
        if (response.code == 1) {
          this.handleCurrentChange(this.currentPage);
          this.scanSetDialog = false;
        }
      });
    },
    scanSetClick(row, index) {
      this.scanForm.id = row.id;
      this.package_list = [];
      this.package_info = row;
      this.is_sweep = row.is_sweep == 1 ? true : false;
      this.is_mida = row.combo_id == 6 ? true : false;
      this.scanForm.combo_id = row.combo_id == 6 ? "" : row.combo_id;
      get_package({ all: 1, brand_id: row.brand_id }).then((response) => {
        this.package_list = response.filter((item, i) => {
          return item.id != 6;
        });
        this.mealChange();
      });
      this.scanSetDialog = true;
    },
    searchClick() {
      this.fetchData();
    },
    // 提交
    saveClick(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.newForm = this.saveForm;
          this.newForm.is_gift_mapping = this.isGiftMapping == true ? 1 : 0;
          if (this.clevice_id) {
            this.newForm.clevice_id = this.clevice_id;
          }
          saveClevice(this.newForm, this.url).then((response) => {
            this.$message({ type: "success", message: response.message });
            if (response.code == 1) {
              this.handleCurrentChange(this.currentPage);
              this.addCleviceDialog = false;
            }
          });
        }
      });
    },
    // 编辑和新增弹框
    addEditClick(id, index) {
      this.dialogTitle = id ? "编辑卡头" : "添加卡头";
      this.editIndex = "";
      this.isAdd = true;
      this.addCleviceDialog = true;
      this.url = "/Machine_clevice/create_machine_clevice"; //新建URL
      if (id) {
        this.url = "/Machine_clevice/update_machine_clevice"; //编辑提交URL
        this.editIndex = index;
        this.isAdd = false;
        this.clevice_id = id;
        this.saveForm.coins_sell_vip = this.list[index].coins_sell_vip;
        this.saveForm.coins_sell = this.list[index].coins_sell;
        this.saveForm.pulse = this.list[index].pulse;
        this.saveForm.remark = this.list[index].remark;
        this.saveForm.type = this.list[index].type;
        this.saveForm.stars = this.list[index].stars == 0 ? '' : this.list[index].stars;
        this.isGiftMapping =
          this.list[index].is_gift_mapping == 1 ? true : false;
        this.saveForm.times = this.list[index].times == 0 ? '' : this.list[index].times;
      } else {
        this.saveForm = {
          type: "",
          machine_id: this.$route.params.machine_id,
          coins_sell_vip: "",
          coins_sell: "",
          pulse: "",
          remark: "",
          is_gift_mapping: "",
          stars: "",
        };
      }
    },

    // 新建卡头
    addCleviceClick() {
      this.$refs["saveForm"].resetFields();
      this.isDisabled = false;
      this.clevice_id = "";
      this.saveForm.remark = "";
      this.isGiftMapping = false;
    },
    // 删除按钮
    delClick(id, index) {
      this.$confirm("此操作删除, 是否继续?", "提示", { type: "warning" }).then(
        () => {
          delClevice({ id: id }).then((response) => {
            if (response.code == 1) {
              this.list.splice(index, 1);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            }
          });
        }
      );
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      this.currentPage = 1;
      getPage(this.formInline)
        .then((response) => {
          this.totalDataNumber = response.count * 1;
          getList(this.formInline).then((response) => {
            this.machineInfo = response.machine;
            this.list = response.list;
            this.listLoading = false;
          });
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    // 分页
    handleCurrentChange(val) {
      this.listLoading = true;
      getList(this.formInline, val).then((response) => {
        this.list = response.list;
        this.listLoading = false;
      });
    },
    //关闭弹框重置
    callOf(formName) {
      this.$refs[formName].resetFields();
      this.addCleviceDialog = false;
      this.isDisabled = false;
      this.clevice_id = "";
      this.saveForm.remark = "";
      this.isGiftMapping = false;
    },
  },
};
</script>
<style>
.el-dialog {
  width: 660px;
}

/*去除table的横向滚动条*/
.el-table--scrollable-x .el-table__body-wrapper::-webkit-scrollbar{
  height: 0;
}

/*表格内容缩进，文字一行展示*/
.el-table td>.cell{
  padding-left: 1px !important;
  padding-right: 1px;
  word-break:keep-all;       /* 不换行 */
  white-space:nowrap;        /* 不换行 */
}
</style>